package com.atguigu.gulimall.product.web.syn;

public class NotSafe {

    public static void main(String[] args) {
        Account account = new Account(100, "学费");
        Drawing d1 = new Drawing(account,50,"小明");
        Drawing d2 = new Drawing(account,100,"小王");
        d1.start();
        d2.start();
    }

}

class Account{

    //账户余额
    protected int money;
    //账户名称
    protected String name;


    public Account(int money,String name){
        this.money = money;
        this.name = name;
    }
}

//模拟银行取钱
class Drawing extends Thread{

    //账户
    protected Account account;
    //取多少钱
    protected int drawing;
    //谁取钱
    protected int nowMoney;

    public Drawing(Account account,int drawing,String name){
        super(name);
        this.account = account;
        this.drawing = drawing;
    }

    @Override
    public void run() {//不能在这里锁定 public synchronized void run synchronized锁定的当前对象
        synchronized (account){//只能这样锁定 synchronized 锁定的是变动的共享空间
            if(account.money - drawing<0){
                System.out.println(this.getName()+"要取"+drawing+",账户剩余"+account.money+"余额不足");
                return;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //卡里的钱
            account.money = account.money - drawing;
            //手里取到的钱
            nowMoney = nowMoney + drawing;
            System.out.println(account.name+"的余额为"+account.money);
            System.out.println(this.getName()+"取到了"+drawing);
        }
    }
}
